package com.jerry.android.VendorDB.Realm;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.jerry.android.R;

import io.realm.Realm;
import io.realm.RealmAsyncTask;
import io.realm.RealmChangeListener;
import io.realm.RealmConfiguration;
import io.realm.RealmQuery;
import io.realm.RealmResults;
import io.realm.Sort;

//        sum()：对指定字段求和。
//        average()：对指定字段求平均值。
//        min(): 对指定字段求最小值。
//        max() : 对指定字段求最大值。count : 求结果集的记录数量。
//        findAll(): 返回结果集所有字段，返回值为RealmResults队列
//        findAllSorted() : 排序返回结果集所有字段，返回值为RealmResults队列
//        between(), greaterThan(),lessThan(), greaterThanOrEqualTo() & lessThanOrEqualTo()
//        equalTo() & notEqualTo()
//        contains(), beginsWith() & endsWith()
//        isNull() & isNotNull()
//        isEmpty()& isNotEmpty()

public class RealmActivity extends AppCompatActivity implements View.OnClickListener{

    private Button btnAdd1, btnAdd2, btnAdd3, btnAdd4, btnAdd5, btnAdd6;
    private Button btnGet1, btnGet2, btnGet3, btnGet4, btnGet5, btnGet6;
    private Button btnModify1;
    private Button btnDelete1;


    private Realm mRealm;
    private RealmAsyncTask transaction5;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_db_realm);

        mRealm = RealmHelper.getInstance().getRealm();

        btnAdd1 = (Button)findViewById(R.id.add1);
        btnAdd1.setOnClickListener(this);
        btnAdd2 = (Button)findViewById(R.id.add2);
        btnAdd2.setOnClickListener(this);
        btnAdd3 = (Button)findViewById(R.id.add3);
        btnAdd3.setOnClickListener(this);
        btnAdd4 = (Button)findViewById(R.id.add4);
        btnAdd4.setOnClickListener(this);
        btnAdd5 = (Button)findViewById(R.id.add5);
        btnAdd5.setOnClickListener(this);
        btnAdd6 = (Button)findViewById(R.id.add6);
        btnAdd6.setOnClickListener(this);

        btnGet1 = (Button)findViewById(R.id.get1);
        btnGet1.setOnClickListener(this);
        btnGet2 = (Button)findViewById(R.id.get2);
        btnGet2.setOnClickListener(this);
        btnGet3 = (Button)findViewById(R.id.get3);
        btnGet3.setOnClickListener(this);
        btnGet4 = (Button)findViewById(R.id.get4);
        btnGet4.setOnClickListener(this);
        btnGet5 = (Button)findViewById(R.id.get5);
        btnGet5.setOnClickListener(this);
        btnGet6 = (Button)findViewById(R.id.get6);
        btnGet6.setOnClickListener(this);

        btnModify1 = (Button)findViewById(R.id.modify);
        btnModify1.setOnClickListener(this);

        btnDelete1 = (Button)findViewById(R.id.delete);
        btnDelete1.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.add1:
                mRealm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        UserBean user = realm.createObject(UserBean.class, 1);
                        user.setName("Gavin");
                        user.setAge(23);
                        user.setDesc("aaaaa");
                    }
                });
                break;

            case R.id.add2:
                final UserBean user = new UserBean();
                user.setId(2);
                user.setName("Jack");
                user.setAge(45);
                mRealm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        realm.copyToRealmOrUpdate(user);
                    }
                });
                break;

            case R.id.add3:
                mRealm.beginTransaction();//开启事务
                UserBean user3 = mRealm.createObject(UserBean.class,3);
                user3.setName("Gavin");
                user3.setAge(4);
                mRealm.commitTransaction();//提交事务
                break;

            case R.id.add4:
                mRealm.executeTransactionAsync(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        UserBean user = realm.createObject(UserBean.class,4);
                        user.setName("Eric");
                        user.setAge(48);
                    }
                });
                break;

            case R.id.add5:
                transaction5 =  mRealm.executeTransactionAsync(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        UserBean user = realm.createObject(UserBean.class,5);
                        user.setName("Eri55c");
                        user.setAge(5);
                    }
                }, new Realm.Transaction.OnSuccess() {
                    @Override
                    public void onSuccess() {
                        //成功回调
                        System.out.println("成功回调");
                    }
                }, new Realm.Transaction.OnError() {
                    @Override
                    public void onError(Throwable error) {
                        //失败回调
                        System.out.println("失败回调");
                    }
                });
                break;

            case R.id.add6:
                //此时会导致崩溃，注意线程的一致性
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        mRealm.executeTransactionAsync(new Realm.Transaction() {
                            @Override
                            public void execute(Realm realm) {
                                UserBean user = realm.createObject(UserBean.class,6);
                                user.setName("Eric666");
                                user.setAge(4866);
                            }
                        });
                    }
                }).start();
                break;

            case R.id.get1:
                //RealmResults继承了AbstractList，而AbstractList又实现了List接口
                RealmResults<UserBean> userList = mRealm.where(UserBean.class).findAll();
                for (UserBean item : userList) {
                    item.toString();
                }
                break;

            case R.id.get2:
//                这里并不会马上查到数据，是有一定延时的。也就是说，你马上使用userList的时候，里面是没有数据的。
//                可以注册RealmChangeListener监听器，或者使用isLoaded()方法，判断是否查询完成
                RealmResults<UserBean> userList2 = mRealm.where(UserBean.class).findAllAsync();

                userList2.addChangeListener(new RealmChangeListener<RealmResults<UserBean>>() {
                    @Override
                    public void onChange(RealmResults<UserBean> element) {
                        for (UserBean item : element) {
                            item.toString();
                        }
                    }
                });
                break;

            case R.id.get3:
                UserBean user2 = mRealm.where(UserBean.class).findFirst();
                user2.toString();
                break;

            case R.id.get4:
//                //得到name为Gavin的用户列表。
//                RealmResults<UserBean> userList3 = mRealm.where(UserBean.class)
//                        .equalTo("name", "Gavin").findAll();

//                //查询dogs.name为二哈的User
//                RealmResults<UserBean> userList3 = mRealm.where(UserBean.class)
//                        .equalTo("dogs.name", "二哈").findAll();

//                //找到用户名为“Gavin”，且dogs.name为“二哈”的User
//                RealmResults<UserBean> userList3 = mRealm.where(UserBean.class)
//                        .equalTo("name", "Gavin")
//                        .equalTo("dogs.name", "二哈")
//                        .findAll();

//                //查询name为“Gavin”和“Eric”的用户
//                RealmQuery<UserBean> query = mRealm.where(UserBean.class);
//                query.equalTo("name", "Gavin");
//                query.or().equalTo("name", "Eric");
//                RealmResults<UserBean> userList3 = query.findAll();

                RealmResults<UserBean> userList3 = mRealm.where(UserBean.class)
                        .equalTo("name", "Gavin")
                        .or().equalTo("name", "Eric")
                        .findAll();

                for (UserBean item : userList3) {
                    item.toString();
                }
                break;

            case R.id.get5:
                RealmResults<UserBean> userList4 = mRealm.where(UserBean.class) .findAll();
//                userList4 = userList4.sort("age"); //根据age，正序排列
                userList4 = userList4.sort("age", Sort.DESCENDING);//逆序排列

                for (UserBean item : userList4) {
                    item.toString();
                }

                break;

            case R.id.get6:
                RealmResults<UserBean> results = mRealm.where(UserBean.class).findAll();
                long   sum     = results.sum("age").longValue();
                long   min     = results.min("age").longValue();
                long   max     = results.max("age").longValue();
                double average = results.average("age");
                long   matches = results.size();
                break;

            case R.id.modify:
                mRealm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        //先查找后得到User对象
                        UserBean user = mRealm.where(UserBean.class).findFirst();
                        user.setAge(26);
                    }
                });
                break;

            case R.id.delete:
                final RealmResults<UserBean> userList5 = mRealm.where(UserBean.class).findAll();
                mRealm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        userList5.get(0).deleteFromRealm();

//                        userList5.deleteFromRealm(0);
//                        userList5.deleteFirstFromRealm(); //删除user表的第一条数据
//                        userList5.deleteLastFromRealm();//删除user表的最后一条数据
//                        userList5.deleteAllFromRealm();//删除user表的全部数据
                    }
                });
                break;

        }
    }

    @Override
    public void onStop () {
        super.onStop();

//        注意：如果在执行findAllAsync时，Acitivity或Fragment被销毁，那么在OnSuccess或OnError中执行UI操作，将导致程序奔溃 。
//        解决办法：在onStop中调用RealmAsyncTask.cancel();可以取消事务，避免crash
        if (transaction5 != null && !transaction5.isCancelled()) {
            transaction5.cancel();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        mRealm.close();
    }
}
